package com.example.chessapp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.util.Timer;
import java.util.TimerTask;

public class RateActivity extends AppCompatActivity implements Runnable {

    EditText rmb;
    TextView result;
    float dollar_r=0.2f;
    float euro_r=0.3f;
    float won_r=0.4f;

    private static final String TAG = "RateActivity";

    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
        rmb = findViewById(R.id.rmb);
        result = findViewById(R.id.result);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate",RateActivity.MODE_PRIVATE);
        dollar_r = sharedPreferences.getFloat("dollar_r",0.1f);
        euro_r = sharedPreferences.getFloat("euro_r",0.2f);
        won_r = sharedPreferences.getFloat("won_r",0.3f);
        Log.i(TAG, "onCreate: dollar=" + dollar_r);
        String updateStr = sharedPreferences.getString("update_str","");
        //获取日期
        LocalDate today = LocalDate.now();
        //比较日期
        if(updateStr.equals(today.toString())){
            Log.i(TAG,"onCreate:日期相等，不更新");
        }else{
            //开启线程
            Thread t = new Thread(this);
            t.start();
        }


        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what==9){
                    String str = (String)msg.obj;
                    Log.i(TAG,"handleMessage:str="+str);
                    result.setText(str);
                    Toast.makeText(RateActivity.this,"数据更新",Toast.LENGTH_SHORT).show();
                    //保存获取的汇率数据
                    SharedPreferences sp = getSharedPreferences("myrate",Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putFloat("dollarRate",dollar_r);
                    editor.putFloat("euroRate",euro_r);
                    editor.putFloat("wonRate",won_r);
                    //存入当前日期
                    editor.putString("update_str",today.toString());
                    editor.apply();
                    Log.i(TAG,"handleMassege: 日期已更新"+today);

                }
                super.handleMessage(msg);
            }
        };

    }

    public void clickRate(View v){

        float r = 0.0f;
        if(v.getId() == R.id.dollar){
            r =dollar_r;
        }else if(v.getId() == R.id.euro){
            r = euro_r;
        }else {
            r =won_r;
        }

        String str = rmb.getText().toString();

        if(str.length()>0 && str != null){
            float a = Float.parseFloat(str);
            float b = a*r;
            String c = String.valueOf(b);
            result.setText(c);
        }else{
            Toast.makeText(this,"请输入人民币",Toast.LENGTH_SHORT).show();
        }

    }

    public void Rateback(View V){
        Intent intent=new Intent(RateActivity.this,MainActivity.class);
        startActivity(intent);
    }

    public void getConfig(View v){
        show();
    }

    private void show() {
        Intent config=new Intent(this, ConfigActivity.class);
        config.putExtra("dollarRate",dollar_r);
        config.putExtra("euroRate",euro_r);
        config.putExtra("wonRate",won_r);
        startActivityForResult(config,1);
    }

    public void getHtmlRate(View v){
        try {
            Document doc = Jsoup.connect("http://usd-cny.com/").get();
            Log.i(TAG, "title:" + doc.title());
            Element table = doc.getElementsByTag("table").first();
            Element tr1 = table.getElementsByTag("tr").get(1);
            Element tr2 = table.getElementsByTag("tr").get(2);
            Element tr6 = table.getElementsByTag("tr").get(6);

            Element dollarRate = tr1.getElementsByTag("td").get(1);
            String dollarRateStr = dollarRate.text();
            dollar_r = Float.parseFloat(dollarRateStr);

            Element euroRate = tr2.getElementsByTag("td").get(1);
            String euroRateStr = euroRate.text();
            euro_r = Float.parseFloat(euroRateStr);

            Element wonRate = tr6.getElementsByTag("td").get(1);
            String wonRateStr = wonRate.text();
            won_r = Float.parseFloat(wonRateStr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //计算页面
        if(requestCode==1&&resultCode==2){
            Bundle bunble=data.getExtras();
            dollar_r=bunble.getFloat("dollarRate",0.1f);
            euro_r=bunble.getFloat("euroRate",0.1f);
            won_r=bunble.getFloat("wonRate",0.1f);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.setting){
            show();
        }
        return super.onOptionsItemSelected(item);
    }

        @Override
        public void run() {
            URL url = null;
            try {
                Document doc = Jsoup.connect("http://usd-cny.com/").get();
                Log.i(TAG, "title:" + doc.title());
                Element table = doc.getElementsByTag("table").first();
                Element tr1 = table.getElementsByTag("tr").get(1);
                Element tr2 = table.getElementsByTag("tr").get(2);
                Element tr6 = table.getElementsByTag("tr").get(6);
                Element dollarRate = tr1.getElementsByTag("td").get(0);
                String dollarRateStr = dollarRate.text();
                dollar_r = Float.parseFloat(dollarRateStr);

                Element euroRate = tr2.getElementsByTag("td").get(1);
                String euroRateStr = euroRate.text();
                euro_r = Float.parseFloat(euroRateStr);

                Element wonRate = tr6.getElementsByTag("td").get(1);
                String wonRateStr = wonRate.text();
                won_r = Float.parseFloat(wonRateStr);

                Log.i(TAG,"run: rate="+dollarRate.text());
                Log.i(TAG,"dollarRateF ="+dollar_r);
                Log.i(TAG,"euroRateF ="+euro_r);
                Log.i(TAG,"wonRateF ="+won_r);

            } catch (IOException e) {
                e.printStackTrace();
            }

            //获取Msg对象，返回主线程
            Message msg = handler.obtainMessage(9);
            msg.obj = "啦啦啦啦~";
            handler.sendMessage(msg);

        }


    private String inputstream2String(InputStream inp) throws IOException{
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inp,"gb2312");
        while (true) {
            int rsz = in.read(buffer,0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer,0, rsz);
        }
        return out.toString();
    }

}
